package com.bxd.baodan.activity;

import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Bitmap;
import android.net.Uri;
import android.net.http.SslError;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AlertDialog;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.animation.Animation;
import android.view.animation.Animation.AnimationListener;
import android.view.animation.AnimationUtils;
import android.webkit.DownloadListener;
import android.webkit.JavascriptInterface;
import android.webkit.JsResult;
import android.webkit.SslErrorHandler;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebSettings.RenderPriority;
import android.webkit.WebStorage;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.Toast;

import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.google.gson.reflect.TypeToken;
import com.bxd.baodan.R;
import com.bxd.baodan.app.Constant;
import com.bxd.baodan.app.JsonApi;
import com.bxd.baodan.app.LoginInfo;
import com.bxd.baodan.item.UserItem;
import com.bxd.baodan.item.WebReadingInfoItem;
import com.bxd.baodan.util.JSONUtil;
import com.bxd.baodan.util.LogUtil;
import com.bxd.baodan.util.NetUtil;
import com.bxd.baodan.util.SpUtil;
import com.bxd.baodan.util.VersionUtil;
import com.bxd.baodan.widget.ShareContentDialog;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

/**
 * 文章不需要传uid
 */
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
@SuppressLint("NewApi")


public class WebViewPager extends BaseActivity {


    private static final String APP_CACHE_DIRNAME = "/webcache";

    public WebView myWebView = null;
    public Handler handler;

    public static final int SHARE_ERROR = 1;
    public static final int SHARE_COMPLETED = 2;
    public static final int SHARE_CANCELED = 3;
    public static final int REFRESH = 1004;
    public static final int SET_TITLE = 90;
    public static final int SHARE_MESSAGE = 92;
    public static final int SHARE_MESSAGE_WITH_TITLE = 93;
    public static final int SHARE_MESSAGE_THREE_PLATFORM = 94;


    private Context nowContext = null;
    private ProgressBar progressbar = null;
    private RelativeLayout loadingLayout = null;
    private String curUrl;// 当前url
    private String short_link;
    private String myUrl = "http://mobi.bxd365.com";


    private int infotype = 0;

    boolean hasSetWebReadingInfo = false;

    public ImageView rightIv;
    public ImageView close;
    private BroadcastReceiver receiveBroadCast;


    String u_id;

    @TargetApi(Build.VERSION_CODES.HONEYCOMB)
    @SuppressLint({"InlinedApi", "SetJavaScriptEnabled", "NewApi"})
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        createHandler();
        setContentView(R.layout.activity_webviewpager);
     // AppManager.getInstance().finishActivity(WelcomeActivity.class);
        Log.e("执行", "WebViewPager ---onCreate: time--:" + System.currentTimeMillis());

        getWindow().setFlags(
                WindowManager.LayoutParams.FLAG_HARDWARE_ACCELERATED,
                WindowManager.LayoutParams.FLAG_HARDWARE_ACCELERATED);

        nowContext = super.getApplicationContext();

        loadingLayout = (RelativeLayout) findViewById(R.id.loading_layout);

        u_id = LoginInfo.getInstance(WebViewPager.this).getUser().getU_id();
        if (u_id == null) {
            u_id = "";
        }
        ImageView actionBarNewBack = (ImageView) findViewById(R.id.bar_iv_back);
        close = (ImageView) findViewById(R.id.bar_iv_close);

        initBroadCastReceiver();


        close.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });

        actionBarNewBack.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                if (myWebView.canGoBack()) {
                    myWebView.goBack();
                } else {
                    finish();
                }
            }
        });

        if (getIntent().getStringExtra("startUrl") != "") {
            myUrl = getIntent().getStringExtra("startUrl");
            // myUrl= "https://ztg.zhongan.com/promote/entrance/promoteEntrance.do?redirectType=h5&promotionCode=INST171047535012&productCode=PRD160436305017&promoteCategory=single_product&token=";
            LogUtil.e("---startUrl----" + myUrl);
        }
        LogUtil.e("url full is " + myUrl);
        progressbar = (ProgressBar) findViewById(R.id.progressBar1);
        rightIv = (ImageView) findViewById(R.id.iv_bar_right);
        rightIv.setImageResource(R.drawable.share);
        rightIv.setVisibility(View.GONE);
        progressbar.setPadding(0, -10, 0, 0);

        if (progressbar.equals("setAlpha")) {
            progressbar.setAlpha(0.6f);
        }

        myWebView = (WebView) findViewById(R.id.webView1);
      //  myWebView.setWebContentsDebuggingEnabled(true);

        initWebView();
        myWebView.setDownloadListener(new MyWebViewDownLoadListener());

        myWebView.loadUrl(myUrl);
        //    myWebView.loadUrl("file:///android_asset/protocol.html");


        // 增加js
        if (myUrl != null) {
            myWebView.addJavascriptInterface(new CustomJS(), "CustomJS");
        }


    }


    private void createHandler() {
        if (handler == null) {
            handler = new Handler() {
                @Override
                public void handleMessage(Message msg) {
                    String platFromName = msg.getData().getString(
                            "platFormName");
                    String id = msg.getData().getString("params");
                    switch (msg.what) {
                        case REFRESH:
                            myWebView.loadUrl(myUrl);
                            break;
                        case ERROR_PAGE:

                            myWebView.loadUrl(Constant.NO_PAGE);
                            break;
                        case SHARE_ERROR:
                            Toast.makeText(WebViewPager.this, "分享失败",
                                    Toast.LENGTH_SHORT).show();
                            break;
                        case SHARE_COMPLETED:
                            Toast.makeText(WebViewPager.this, "分享成功",
                                    Toast.LENGTH_SHORT).show();
                                                        NetUtil netUtil = new NetUtil(WebViewPager.this,
                                                                JsonApi.SHARE);
                                                        netUtil.setParams("platform", platFromName);
                                                        netUtil.setParams("id", id);
                                                        try {
                                                            netUtil.setParams("url",
                                                                    URLEncoder.encode(curUrl, "UTF-8"));
                                                        } catch (UnsupportedEncodingException e) {
                                                            e.printStackTrace();
                                                        }
                                                        netUtil.postRequest("", new NetUtil.RequestStringListener() {
                                                            @Override
                                                            public void onComplete(String result) {
                                                                LogUtil.e("------分享成功------------");
                                                            }
                                                        });




                            break;
                        case SHARE_CANCELED:
                            Toast.makeText(WebViewPager.this, "取消分享",
                                    Toast.LENGTH_SHORT).show();
                            break;
                        default:
                            break;
                    }
                }

            };
        }
    }

    @SuppressLint({"SetJavaScriptEnabled", "JavascriptInterface"})
    private void initWebView() {

       //启用WebView调试
//        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
//            WebView.setWebContentsDebuggingEnabled(true);
//        }

        myWebView.getSettings().setJavaScriptEnabled(true);
        myWebView.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);

        myWebView.getSettings().setRenderPriority(RenderPriority.HIGH);

        myWebView.getSettings().setDomStorageEnabled(true);
        myWebView.getSettings().setAppCacheMaxSize(1024 * 1024 * 8);
        String appCacheDir = this.getApplicationContext()
                .getDir("cache", Context.MODE_PRIVATE).getPath();
        myWebView.getSettings().setAppCachePath(appCacheDir);
        myWebView.getSettings().setAllowFileAccess(true);
        myWebView.getSettings().setAppCacheEnabled(true);
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP) {
            myWebView.getSettings().setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
        }
        myWebView.getSettings().setDomStorageEnabled(true);


        // FIXME: 2017/5/27 修改缓存模式
        myWebView.getSettings().setCacheMode(WebSettings.LOAD_DEFAULT);
        myWebView.getSettings().setPluginState(WebSettings.PluginState.ON);
        // android:hardwareAccelerated="true" 需要在Manifest.xml中加入启用硬件加速功能

        String UA = myWebView.getSettings().getUserAgentString();
        myWebView.getSettings().setUserAgentString(UA + " / Wenwen Browser");

        myWebView.setWebViewClient(new CustomWebViewClient());
        myWebView.setWebChromeClient(new CustomWebChromeClient());
        myWebView.requestFocus();
        // 设置缩放功能
        //		myWebView.getSettings().setSupportZoom(true);
        //		myWebView.getSettings().setBuiltInZoomControls(true);

        myWebView.setLongClickable(false);

    }





    public JSONObject addMenu = null;
    public int setMenuDisplay = 0;

    public JSONArray jsStartRun = new JSONArray();

    private Handler jsHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case SET_TITLE:
                    setActionBarTitle(msg.obj.toString());
                    break;

                case SHARE_MESSAGE_WITH_TITLE:
                    try {
                        JSONObject extras = new JSONObject(msg.obj.toString());
                        shareMessage(extras.getString("content"),
                                extras.getString("imgUrl"),
                                extras.getString("shortlink"),
                                /*extras.getString("params"),*/ extras.getString("title"));
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                    break;
                case SHARE_MESSAGE:
                    try {
                        JSONObject extras = new JSONObject(msg.obj.toString());
                        shareMessage(extras.getString("title"), extras.getString("content"),
                                extras.getString("imgUrl"),
                                extras.getString("shortlink"),
                                extras.getString("shortlink"));
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                    break;


                case SHARE_MESSAGE_THREE_PLATFORM:
                    Bundle b = msg.getData();

                    shareMessage(b.getString("title"), b.getString("content"),
                            b.getString("image"),
                            b.getString("url"),
                            b.getString("url"));

                    break;

                default:
                    break;
            }
        }
    };

    public class CustomJS {

        private boolean checkJSauth() {
            return true;
        }


        /**
         * 如意岛分享调用方法
         * 分享
         * title      string , 分享标题
         * content    string ，分享内容
         * image      string ，图片地址
         * url        string ，跳转地址
         */
        @JavascriptInterface
        public void wap_share(String title, String content, String image, String url) {
            Message msg = new Message();
            msg.what = SHARE_MESSAGE_THREE_PLATFORM;
            Bundle b = new Bundle();
            b.putString("title", title);
            b.putString("content", content);
            b.putString("image", image);
            b.putString("url", url);
            msg.setData(b);

            jsHandler.sendMessage(msg);
        }

        /**
         * 如意岛授权方法
         * 发起授权
         * redirect_url        string ，同意授权后跳转地址
         * platform            string , 平台类型，（优财：yc，保险岛：bxd，助手：zs，智慧魔方：zhmf）
         */
        @JavascriptInterface
        public void wap_auth(String redirect_url, String platform) {
            NetUtil netUtil = new NetUtil(WebViewPager.this, JsonApi.AUTH_CHECKISAUTH);
            netUtil.setParams("from", platform);
            netUtil.setParams("url", redirect_url);
            final String url = redirect_url;
            final String plat = platform;
            netUtil.postRequest("", new NetUtil.RequestStringListener() {
                @Override
                public void onComplete(String result) {
                    if (JSONUtil.getData("isAuth", JSONUtil.getData(result)).equals("0")) {
                        Intent intent = new Intent();
                        intent.putExtra("redirect_url", url);
                        intent.putExtra("platform", plat);
                        intent.setClass(WebViewPager.this, OAuthActivity.class);

                        startActivityForResult(intent, 300);
                        //  openActivity(OAuthActivity.class, new String[]{"redirect_url", "platform"}, new String[]{url, plat});
                    } else if (JSONUtil.getData("isAuth", JSONUtil.getData(result)).equals("1")) {
                        myUrl = JSONUtil.getData("redirectUrl", JSONUtil.getData(result));
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                myWebView.loadUrl(myUrl);
                            }
                        });

                    }
                }


            });


        }


        @JavascriptInterface
        public void refreshWebView() {
            Message msg = new Message();
            msg.what = REFRESH;
            handler.sendMessage(msg);

        }


        @JavascriptInterface
        public void setWebReadingInfo(String webmsg) {
            LogUtil.e("--setWebReadingInfo--webmsg:" + webmsg);
            hasSetWebReadingInfo = true;
            WebReadingInfoItem item = new Gson().fromJson(webmsg,
                    new TypeToken<WebReadingInfoItem>() {
                    }.getType());


            if (item.getBasemsg() != null) {
                //微阅读消息
                SpUtil.getInstance().savaString("web_title",
                        item.getBasemsg().getTitle());
                SpUtil.getInstance().savaString("imgUrl",
                        item.getBasemsg().getImgurl());   //imgurl
                SpUtil.getInstance().savaString("short_link",
                        item.getBasemsg().getShortLink()); //shortLink
                short_link = item.getBasemsg().getShortLink();

                SpUtil.getInstance().savaString("temId",
                        item.getBasemsg().getInfoId()); //InfoId


                infotype = Integer.parseInt(item.getBasemsg().getTypeId());
            } else {
                //产品消息
                short_link = JSONUtil.getData("shortlink", webmsg);
                SpUtil.getInstance().savaString("imgUrl",
                        JSONUtil.getData("imgurl", webmsg));   //imgurl
                SpUtil.getInstance().savaString("content",
                        JSONUtil.getData("content", webmsg));
                SpUtil.getInstance().savaString("shortlink",
                        JSONUtil.getData("shortlink", webmsg));
                SpUtil.getInstance().savaString("web_title",
                        JSONUtil.getData("title", webmsg));
            }

            LogUtil.e("----infotype----" + infotype);

        }

        // 设置title
        @JavascriptInterface
        public void setTitle(final String title) {
            Message msg = new Message();
            msg.what = SET_TITLE;
            msg.obj = title;
            jsHandler.sendMessage(msg);

        }


        /*
         * 获取问题id
         */
        @JavascriptInterface
        public void showQuestion(String qid, String u_nike) {
            if (checkJSauth()) {
                Intent intent = new Intent(WebViewPager.this,
                        QuestionDetailActivity.class);
                intent.putExtra("qid", qid);
                intent.putExtra("u_nike", u_nike);
                WebViewPager.this.startActivity(intent);
                overridePendingTransition(R.anim.slide_in_right,
                        R.anim.slide_out_left);
            }
        }

        /*
         * 跳转
         */
        @JavascriptInterface
        public void showUI(String app) {
            if (checkJSauth()) {
                Intent intent = new Intent();
                ComponentName cn = new ComponentName("com.bxd.baodan",
                        "com.bxd.baodan.activity."
                                + (new Gson().fromJson(app, JsonObject.class))
                                .get("class").toString()
                                .replace("\"", ""));
                intent.putExtra("startUrl", JSONUtil.getData("url", app));
                intent.setComponent(cn);
                startActivity(intent);
            }
        }


        /*
         * 获取user信息
         */
        @JavascriptInterface
        public String getUserInfo() {
            if (checkJSauth()) {
                UserItem user;
                user = LoginInfo.getInstance(getApplicationContext()).getUser();

                return (new Gson()).toJson(user).toString();
            }

            return null;
        }

        @JavascriptInterface
        public String getVersion() {
            return VersionUtil.getVersionName(WebViewPager.this);
        }

        @JavascriptInterface
        public void share(String extra) {
            Message msg = new Message();
            msg.what = SHARE_MESSAGE;
            msg.obj = extra;
            jsHandler.sendMessage(msg);
        }


        /*
         * 启动activity
         */
        @JavascriptInterface
        public void showActivity(String actname, String extra) {
            String actPrex = "com.bxd.baodan.activity.";
            if (checkJSauth()) {
                try {


                    if (actname.equals("WebViewPager")) {
                        JSONObject jsonObject = new JSONObject(extra);
                        Intent intent = new Intent(WebViewPager.this,
                                WebViewPager.class);

                        intent.putExtra("startUrl", jsonObject
                                .getString("startUrl"));
                        WebViewPager.this.startActivity(intent);
                        overridePendingTransition(R.anim.slide_in_right,
                                R.anim.slide_out_left);
                        // FIXME: 18/1/24 个人报告需要传type,从网页传的时候为修改保费或者其他功能
                    } else if (actname.equals("PersonalDesignActivity")) {
                        LogUtil.e("extra:--------------- " + extra);
                        String sub = extra.substring(extra.indexOf("{"));
                        //  "dic":"{"reportId":"10495","type":"2","role":"spouse"}"
                        String reportId = JSONUtil.getData("reportId", sub);
                        String type = JSONUtil.getData("type", sub);
                        String role = JSONUtil.getData("role", sub);

                        openActivity(PersonalDesignActivity.class,
                                new String[]{"reportId", "type", "role"}, new String[]{reportId, type, role});


                    } else {
                        if (actname.equals("SHARE")) {
                            Message msg = new Message();
                            msg.what = SHARE_MESSAGE;
                            msg.obj = extra;
                            jsHandler.sendMessage(msg);
                            // 以上代表内容，图片地址，短连接，文章id
                        } else if (actname.equals("SHARE_WITH_TITLE")) {
                            Message msg = new Message();
                            msg.what = SHARE_MESSAGE_WITH_TITLE;
                            msg.obj = extra;
                            jsHandler.sendMessage(msg);
                        } else {
                            Class<?> ass = Class.forName(actPrex + actname);
                            if (ass != null) {
                                Intent intent = new Intent(WebViewPager.this, ass);
                                startActivity(intent);
                                overridePendingTransition(R.anim.slide_in_right,
                                        R.anim.slide_out_left);
                            }
                        }
                    }
                } catch (Exception e) {
                    // showToast("调用失败");
                    LogUtil.e("ERROR  : WebViewPager : " + e.getMessage());
                    Class<?> ass = null;
                    try {
                        ass = Class.forName(actPrex + actname);
                        if (ass != null) {
                           openActivity(ass);
                        }
                    } catch (ClassNotFoundException e1) {
                        // TODO Auto-generated catch block
                        e1.printStackTrace();
                    }

                }
            }
        }
    }


    private void showShareIcon(boolean show) {


        //判断url类型
        rightIv.setVisibility(show ? View.VISIBLE : View.GONE);

        rightIv.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                // 分享
                //修复无网络状态下分享崩溃
                if (short_link == null) {
                    return;
                }

                String imgUrl = SpUtil.getInstance().getString("imgUrl");

                if (!imgUrl.contains("http")) {
                    imgUrl = Constant.root_url + imgUrl;
                }
                shareMessage(SpUtil.getInstance().getString("content"),
                        imgUrl,
                        short_link, short_link);
            }
        });


    }





    private void shareMessage(String content, String imgUrl, String shortLink,
                              String id) {
        // TODO: 2017/8/10  
        ShareContentDialog scd = new ShareContentDialog(this,
                SpUtil.getInstance().getString("web_title"), content, shortLink,
                imgUrl, id, handler);
        scd.show();

    }

    private void shareMessage(String title, String content, String imgUrl, String shortLink,
                              String id) {
        ShareContentDialog scd = new ShareContentDialog(this, title, content,
                shortLink, imgUrl
                , id, handler);
        scd.show();
    }


    public void clearWebViewCache() {

        try {
            deleteDatabase("webview.db");
            deleteDatabase("webviewCache.db");
        } catch (Exception e) {
            e.printStackTrace();
        }

        File appCacheDir = new File(getFilesDir().getAbsolutePath()
                + APP_CACHE_DIRNAME);

        File webviewCacheDir = new File(getCacheDir().getAbsolutePath()
                + "/webviewCache");

        if (webviewCacheDir.exists()) {
            deleteFile(webviewCacheDir);
        }
        if (appCacheDir.exists()) {
            deleteFile(appCacheDir);
        }
    }

    /**
     * @param file
     */
    public void deleteFile(File file) {

        //	Log.i(TAG, "delete file path=" + file.getAbsolutePath());

        if (file.exists()) {
            if (file.isFile()) {
                file.delete();
            } else if (file.isDirectory()) {
                File files[] = file.listFiles();
                for (File file1 : files) {
                    deleteFile(file1);
                }
            }
            file.delete();
        } else {
            //		Log.e(TAG, "delete file no exists " + file.getAbsolutePath());
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {

        if (keyCode == KeyEvent.KEYCODE_BACK) {

            if (myWebView.canGoBack()) {
                if (curUrl.equals(Constant.NO_PAGE)) {
                    this.finish();
                    return true;
                }

                curUrl = "";
                myWebView.goBack();
                return true;
            }
        }
        return super.onKeyDown(keyCode, event);
    }

    private static final int ERROR_PAGE = 404;

    public class CustomWebViewClient extends WebViewClient {

        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {
            curUrl = url;
            if (!url.equals(Constant.NO_PAGE)) {
                myUrl = url;
            }
            loadingLayout.setVisibility(View.VISIBLE);

        }

        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            LogUtil.e("----url-----" + url);
            try {
                if (url.startsWith("tel:")) {
                    Intent intent = new Intent(Intent.ACTION_DIAL,
                            Uri.parse(url));
                    startActivity(intent);
                    overridePendingTransition(R.anim.slide_in_right,
                            R.anim.slide_out_left);
                } else if (url.startsWith("http:") || url.startsWith("https:")) {

                    view.loadUrl(url);

                } else if (url.contains("weixin://")) { // 打开微信 众安需要
                    Uri uri = Uri.parse(url);
                    Intent intent = new Intent(Intent.ACTION_VIEW, uri);
                    try {
                        startActivity(intent);
                    } catch (Exception e) {
                        new AlertDialog.Builder(context)
                                .setMessage("未检测到微信客户端，请安装后重试。")
                                .setPositiveButton("知道了", null).show();
                    }
                    return true;
                } else if (url.startsWith("alipays:") || url.startsWith("alipay")) { // 支付宝 调出APP
                    try {
                        context.startActivity(new Intent("android.intent.action.VIEW", Uri.parse(url)));
                    } catch (Exception e) {
                        new AlertDialog.Builder(context)
                                .setMessage("未检测到支付宝客户端，请安装后重试。")
                                .setPositiveButton("立即安装", new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {
                                        Uri alipayUrl = Uri.parse("https://d.alipay.com");
                                        context.startActivity(new Intent("android.intent.action.VIEW", alipayUrl));
                                    }
                                }).setNegativeButton("取消", null).show();
                    }
                    return true;
                }

            } catch (Exception e) {
                showToast("页面打开异常");
                finish();
            }
            return true;
        }

        @Override
        public void onPageFinished(WebView view, String url) {
            //showToast("onPageFinished--" +"hasSetWebReadingInfo" + hasSetWebReadingInfo );
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    if (myWebView.canGoBack()) {
                        close.setVisibility(View.VISIBLE);
                    } else {
                        close.setVisibility(View.GONE);
                    }
                    showShareIcon(hasSetWebReadingInfo);
                    hasSetWebReadingInfo = false;
                }
            });


            //  html加载完成之后，调用js的方法
            //  imgReset();
            Animation anim = AnimationUtils.loadAnimation(nowContext,
                    R.anim.fade_out);
            loadingLayout.startAnimation(anim);
            anim.setAnimationListener(new AnimationListener() {

                @Override
                public void onAnimationEnd(Animation animation) {
                    loadingLayout.setVisibility(View.GONE);
                }

                @Override
                public void onAnimationStart(Animation animation) {
                }

                @Override
                public void onAnimationRepeat(Animation animation) {
                }

            });
        }


        @Override
        public void onReceivedError(WebView view, int errorCode,
                                    String description, String failingUrl) {
            view.stopLoading();
            view.clearView();
            Message msg = handler.obtainMessage();// 发送通知，加入线程
            msg.what = ERROR_PAGE;// 通知加载自定义404页面
            handler.sendMessage(msg);// 通知发送！
        }


        @Override
        public void onReceivedSslError(WebView view,
                                       SslErrorHandler handler, SslError error) {
            handler.proceed();
        }


    }


    public class CustomWebChromeClient extends WebChromeClient {

        @Override
        public void onProgressChanged(WebView view, int newProgress) {

            if (newProgress < 5) {
                newProgress = 5;
            }

            progressbar.setProgress(newProgress);

            if (newProgress == 100) {
                progressbar.setVisibility(View.GONE);
            } else {
                progressbar.setVisibility(View.VISIBLE);
            }

            super.onProgressChanged(view, newProgress);

        }

        @Override
        public boolean onJsAlert(WebView view, String url, String message,
                                 JsResult result) {
            showToast(message);
            result.cancel();
            return true;

        }

        @Override
        public void onReceivedTitle(WebView view, String title) {


            try {
                if (title.length() > 11) {
                    String str = title.substring(0, 10) + "...";
                    setActionBarTitle(str);
                } else {
                    setActionBarTitle(title);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }


        }


        @Override
        public void onReachedMaxAppCacheSize(long spaceNeeded,
                                             long totalUsedQuota, WebStorage.QuotaUpdater quotaUpdater) {
            quotaUpdater.updateQuota(spaceNeeded * 2);
        }

    }

    @Override
    protected void onDestroy() {

        RelativeLayout _layout = (RelativeLayout) findViewById(R.id.webviewRelativeLayout);
        try {
            _layout.removeView(myWebView);
        } catch (Exception e) {
            e.printStackTrace();
        }
        myWebView.removeAllViews();
        myWebView.destroy();
        myWebView.setVisibility(View.GONE);

        if (handler != null) {
            handler.removeCallbacksAndMessages(null);
        }
        if (jsHandler != null) {
            jsHandler.removeCallbacksAndMessages(null);
        }

        try {
            this.unregisterReceiver(receiveBroadCast);
        } catch (Exception e) {

        }

        super.onDestroy();
    }

    @Override
    public void finish() {
        // TODO Auto-generated method stub
        ViewGroup view = (ViewGroup) getWindow().getDecorView();
        view.removeAllViews();

        super.finish();
        if (handler != null) {
            handler.removeCallbacksAndMessages(null);
        }
        if (jsHandler != null) {
            jsHandler.removeCallbacksAndMessages(null);
        }


    }


    private class MyWebViewDownLoadListener implements DownloadListener {

        @Override
        public void onDownloadStart(String url, String userAgent, String contentDisposition, String mimetype,
                                    long contentLength) {
            Uri uri = Uri.parse(url);
            Intent intent = new Intent(Intent.ACTION_VIEW, uri);
            startActivity(intent);
        }

    }

    // 回调方法，从第二个页面回来的时候会执行这个方法
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {

        if (resultCode == 300) {
            myUrl = data.getStringExtra("url");
            myWebView.loadUrl(myUrl);
        }

    }

    private void initBroadCastReceiver() {
        receiveBroadCast = new ReceiveBroadCast();
        IntentFilter filter = new IntentFilter();
        filter.addAction(Constant.ACTION_SUCCESS_LOGIN);
        this.registerReceiver(receiveBroadCast, filter);
    }

    class ReceiveBroadCast extends BroadcastReceiver {

        @Override
        public void onReceive(Context arg0, Intent arg1) {

            if (Constant.ACTION_RECEIVE_MSG.equals(arg1.getAction())) {

            } else if (Constant.ACTION_LOGIN_LOGINOUT.equals(arg1.getAction())) {

            } else if (Constant.ACTION_SUCCESS_LOGIN.equals(arg1.getAction())) {
                myWebView.loadUrl(myUrl);
            }
        }

    }

}
